﻿namespace Jhong.FunMVC
{
    using System.Threading.Tasks;

    internal class MVCHandler
    {
        private Request _request;

        private Response _reponse;

        private RouteBase _routeBase;

        internal MVCHandler(RouteBase routeBase, Request request, Response response)
        {
            this._request = request;
            this._reponse = response;
            this._routeBase = routeBase;
        }

        internal Task Hand()
        {
            var controllerContext = new ControllerContext()
            {
                Response = this._reponse,
                Request = this._request,
                RouteBase = this._routeBase
            };
            ControllerFactory.CreateControllerInstance(ref controllerContext);
            if (null == controllerContext.Controller)
            {
                ThrowExceptionHandler.ThrowException(this._request, this._reponse, new PageNotFoundException());
                return CompletionTask.CompleteTask;
            }
            controllerContext.Controller.Execute(controllerContext);
            controllerContext.Response.PushOutput();
            return CompletionTask.CompleteTask;
        }
    }
}